package com.sky.controller.user;/*
 * ClassName: addressBookController
 * Package : com.sky.controller.user
 * Description:
 * @Author zKer
 * @Create 2024/4/19 10:47
 */

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.addressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user/addressBook")
@Api(tags = "地址簿相关接口")
@Slf4j
public class addressBookController {
    @Autowired
    private addressBookService addressBookService;

    @PostMapping()
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址:{}", addressBook);
        addressBookService.save(addressBook);
        return Result.success();
    }

    @GetMapping("list")
    public Result<List<AddressBook>> list() {
        log.info("查看地址簿");
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> lists = addressBookService.list(addressBook);
        return Result.success(lists);
    }

    @GetMapping("{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("根据id查询地址:{}", id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping()
    @ApiOperation("修改地址")
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("修改地址:{}", addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    @PutMapping("default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址:{}", addressBook);
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    @DeleteMapping()
    @ApiOperation("删除地址")
    public Result delete(Long id) {
        log.info("删除地址:{}", id);
        addressBookService.deleteById(id);
        return Result.success();
    }

    @GetMapping("default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> getDefault() {
        log.info("查询默认地址");
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        List<AddressBook> list = addressBookService.list(addressBook);
        if (list.size() == 1 && list != null) {
            return Result.success(list.get(0));
        }
        return Result.error("没有默认地址");
    }
}
